package com.luhui.codereview.actions

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.ui.components.JBTabbedPane
import com.luhui.codereview.URL_PREFIX
import com.luhui.codereview.UserGroupIcon
import com.luhui.codereview.getMessage
import com.luhui.codereview.service.ProjectService
import com.luhui.codereview.token.LocalUserInfoHodler
import java.awt.EventQueue
import java.awt.FlowLayout
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.io.File
import java.net.URL
import javax.imageio.ImageIO
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JLabel

/**
 * @author luhui
 * @version 1.0
 * @date 2019/11/18 22:08
 */
class CreateUserGroupAction(
        private val project: Project,
        private val jBTabbedPane:JBTabbedPane?
) : AnAction(getMessage("tab.refresh.action.userGroupText"), getMessage("tab.refresh.action.userGroupText"), UserGroupIcon){
    override fun actionPerformed(p0: AnActionEvent?) {
        // 请求服务端生成二维码
        val jFrame = JFrame(getMessage("qrFrame.title"))
        val projectId = ProjectService.getInstance(project).getCurrentProjectInfo()?.id
        if (projectId == null) {
            EventQueue.invokeLater {
                Messages.showErrorDialog(getMessage("notFoundProjectId.msg"), getMessage("notFoundProjectId.title"))
            }
            return
        }
        val userId = LocalUserInfoHodler.localUserInfo?.id
        if (userId == null) {
            EventQueue.invokeLater {
                Messages.showErrorDialog(getMessage("qrFrame.onNotAuth"), getMessage("qrFrame.onNotAuth.title"))
            }
            jBTabbedPane?.selectedIndex = 2
            return
        }
        val url = URL("${URL_PREFIX}cr/review/getReviewQRCode?userId=${LocalUserInfoHodler.localUserInfo?.id}&projectId=$projectId")
        val image = ImageIO.read(url)
        val c = jFrame.contentPane
        c.layout = FlowLayout()
        val jLabel = JLabel()
        c.add(jLabel)
        jLabel.icon = ImageIcon(image)
        jFrame.setBounds(200, 100, 500, 350)
        jFrame.setLocationRelativeTo(null)
        jFrame.isVisible = true
        jLabel.addMouseListener(object : MouseAdapter() {
            override fun mouseClicked(e: MouseEvent?) {
                val descriptor = FileChooserDescriptor(false, true, false, false, false, false)
                descriptor.title = getMessage("saveQrCode.title")
                descriptor.withFileFilter {
                    it.path.endsWith(".jpg")
                }
                val virtualFile = FileChooser.chooseFile(descriptor, project, null)

                if (virtualFile != null) {
                    val path = virtualFile.path
                    var fileName = "qrImg"
                    val suffix = ".jpg"
                    var file = File(path, "$fileName$suffix")
                    while (file.exists()) {
                        fileName += "0"
                        file = File(path, "$fileName$suffix")
                    }
                    ImageIO.write(image, "jpeg", file)
                    Runtime.getRuntime().exec("explorer /select, ${file.path}")
                }
            }
        })
    }

    override fun displayTextInToolbar(): Boolean {
        return true
    }
}
